﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZK.YHP_TransManage.Com;
using ZK.Common;
using System.Threading;
using ZK.InterfaceServer;
using System.Diagnostics;
using System.Timers;
using ZK.HardWareBLL;

namespace ZK.YHP_TransManage.UC
{
    /// <summary>
    /// 轻磅-自动过磅
    /// </summary>
    public partial class LightWeight : UserControl
    {
        private string NowCarNum = "";//当前车牌
        private string CameraIp = "";//已识别到车牌的车牌识别一体机的ip
        private string NowCardNum = "";//当前卡号
        public CameraBLL cameraQ;
        public CameraBLL cameraG1;
        public CameraBLL cameraG2;
        private HardWareBLL.YRTReaderBLL yRTReaderBLL;
        public string cardNumNow = string.Empty;
        System.Timers.Timer rePeatCardNumTimer =
           new System.Timers.Timer(Convert.ToInt32(AppConfigHelper.GetAppSettings("RePeatCardNumTime")));
        System.Timers.Timer noCarTimer =
           new System.Timers.Timer(Convert.ToInt32(AppConfigHelper.GetAppSettings("NoCarTime")));

        public HardWareBLL.Onbon6K1CardBLL onbon6K1CardBLL;
        string WeighbridgeId;
        int clearTextTime;
        bool redLightState;

        /// <summary>
        /// 当前重量
        /// </summary>
        public double nowWeight = 0;

        private static readonly object obj = new object();

        MW_102N_CardReader mW_102N_CardReader;

        TrafficLightBLL trafficLightQ;
        LingShengAudioBLL lingShengAudio;
        ToledoWagonBalanceBLL toledoWagonBalanceBLL;
        InfraredGratingBLL infraredGrating;

        /// <summary>
        /// 页面加载完后的定时器
        /// </summary>
        System.Timers.Timer loadTaskTimer = new System.Timers.Timer(1000);
        private bool LoadTaskState = false;


        /// <summary>
        /// 地磅重量标准
        /// </summary>
        private double weightBZ;
        /// <summary>
        /// 地磅是否有数据
        /// </summary>
        private bool weightHaveDate;
        /// <summary>
        /// 红外数据
        /// </summary>
        private int InfraredGratingDate;
        /// <summary>
        /// 运销车辆信息
        /// </summary>
        private Models.GetTruckYxInfoRceiveM yxYsTransportReturnDto;
        /// <summary>
        /// 红外遮挡时间间隔
        /// </summary>
        private int InfraredGratingTime;

        /// <summary>
        /// 摄像头已经识别的车牌列表
        /// </summary>
        private Dictionary<string, string> CarNumList = new Dictionary<string, string>();
        private WFAutoSizeHelper wFAutoSizeHelper = new WFAutoSizeHelper();

        /// <summary>
        /// 构造函数
        /// </summary>
        public LightWeight()
        {
            InitializeComponent();
            wFAutoSizeHelper.GetAllInitInfo(this.Controls[0], this);
        }

        /// <summary>
        /// 初始化红外光栅
        /// </summary>
        private void InitInfraredGrating()
        {
            infraredGrating = new InfraredGratingBLL();
            infraredGrating.Open();
        }

        /// <summary>
        /// 红外光栅委托
        /// </summary>
        /// <param name="data"></param>
        private void InfraredGratingEvent1(int data)
        {
            //
            InfraredGratingDate = data;
        }

        /// <summary>
        /// 红外是否有遮挡的判断
        /// </summary>
        public void InfraredGratingJudge()
        {
            if (InfraredGratingDate != 3)
            {
                Thread.Sleep(InfraredGratingTime);
                LedPageShow(Com.TipsStringHelper.hwgsyzl);
                InfraredGratingJudge();
            }
        }

        /// <summary>
        /// 初始化led
        /// </summary>
        private void InitLed()
        {
            onbon6K1CardBLL = new HardWareBLL.Onbon6K1CardBLL();
            LedPageShow(TipsStringHelper.Hyy);
        }



        /// <summary>
        /// 地磅数据回调委托
        /// </summary>
        /// <param name="weight"></param>
        private void WeightCallback(double weight)
        {
            if (weight != -1)
            {
                nowWeight = weight;
                SetWeightDataInPage();
                //是否大于标吨
                if (weight > weightBZ && !weightHaveDate)
                {
                    trafficLightQ.RedLight();
                    weightHaveDate = true;

                }
                if (weight < weightBZ && weightHaveDate)
                {
                    ClearText();
                    trafficLightQ.GreenLight();
                    weightHaveDate = false;

                }
                //if (weight < weightBZ && weightHaveDate)
                //{
                //    ClearText();
                //    weightHaveDate = false;

                //    redLightState = false;
                //}
                //if (weight > weightBZ && !weightHaveDate && !redLightState)
                //{
                //    trafficLightQ.RedLight();
                //    redLightState = true;
                //}


            }
        }

        /// <summary>
        /// 将委托的数据赋值给页面
        /// </summary>
        public void SetWeightDataInPage()
        {

            this.Invoke(new Action(() =>
            {
                label4.Text = nowWeight.ToString();
            }));
        }

        /// <summary>
        /// 清除页面数据
        /// </summary>
        private void ClearText()
        {
            Task.Factory.StartNew(() =>
            {
                // Thread.Sleep(clearTextTime);
                this.Invoke(new Action(() =>
                {
                    textBoxCardNum.Text = "";
                    textBoxCarNum.Text = "";
                    textBoxKZT.Text = "";
                    textBoxLX.Text = "";
                    textBoxHWMC.Text = "";
                    textBoxCYS.Text = "";
                    textBoxGSM.Text = "";
                    textBoxBZ.Text = "";
                    //textBoxCZZL.Text = "";
                }));
                yxYsTransportReturnDto = new Models.GetTruckYxInfoRceiveM();
                LedPageShow(Com.TipsStringHelper.Hyy);
                //trafficLightQ.GreenLight();
            });
        }

        /// <summary>
        /// 设置页面数据
        /// </summary>
        private void SetText()
        {
            if (string.IsNullOrWhiteSpace(yxYsTransportReturnDto.cardNo))
            {
                return;
            }
            this.Invoke(new Action(() =>
            {
                textBoxKZT.Text = Enum.GetName(typeof(SysDefinitionEnum.SendType), yxYsTransportReturnDto.sendType);
                textBoxCYS.Text = yxYsTransportReturnDto.carrierName;
                textBoxGSM.Text = yxYsTransportReturnDto.shipperName;
                textBoxHWMC.Text = yxYsTransportReturnDto.coalName;
                textBoxBZ.Text = yxYsTransportReturnDto.memo;
                textBoxLX.Text = Enum.GetName(typeof(SysDefinitionEnum.YxState), yxYsTransportReturnDto.yxState);
            }));
        }

        /// <summary>
        /// 初始化地磅
        /// </summary>
        private void InitWagonBalance()
        {
            toledoWagonBalanceBLL = new ToledoWagonBalanceBLL();
        }

        /// <summary>
        /// 初始化菱声网络音响
        /// </summary>
        private void InitLingSheng()
        {
            lingShengAudio = new LingShengAudioBLL();
        }

        /// <summary>
        /// 初始化红绿灯
        /// </summary>
        private void IniTrafficLight()
        {
            trafficLightQ = new TrafficLightBLL(Common.IConfig.GetSetTrafficLightQ);
            trafficLightQ.GreenLight();
        }

        /// <summary>
        /// 初始化室外读卡器
        /// </summary>
        private void InitReader()
        {
            mW_102N_CardReader = new MW_102N_CardReader();
        }

        /// <summary>
        /// 初始化摄像头
        /// </summary>
        private void InitCamera()
        {
            //Q
            {
                Common.HaredWareCommonM cameraScalesQ = Common.IConfig.GetSetCameraScalesQ;
                Common.CameraModel cameraModelQ = new Common.CameraModel()
                {
                    Name = cameraScalesQ.Name,
                    Ip = cameraScalesQ.Ip,
                    Port = Convert.ToInt32(cameraScalesQ.Port),
                    PassWord = cameraScalesQ.PassWord,
                    UserName = cameraScalesQ.UserName
                };
                PageShow("cameraModelQ 初始化");
                cameraQ = new CameraBLL(cameraModelQ);
                cameraQ.ManualOne(pictureBoxQ);
            }

            //G1
            {
                Common.HaredWareCommonM cameraScalesG1 = Common.IConfig.GetSetCameraScalesG1;
                Common.CameraModel cameraModelG1 = new Common.CameraModel()
                {
                    Ip = cameraScalesG1.Ip,
                    Name = cameraScalesG1.Name,
                    Port = Convert.ToInt32(cameraScalesG1.Port),
                    PassWord = cameraScalesG1.PassWord,
                    UserName = cameraScalesG1.UserName
                };
                PageShow("cameraModelG1 初始化");
                cameraG1 = new CameraBLL(cameraModelG1);
                cameraG1.ManualOne(pictureBoxG1);
            }
            //G2
            {
                Common.HaredWareCommonM cameraScalesG2 = Common.IConfig.GetSetCameraScalesG2;
                Common.CameraModel cameraModelG2 = new Common.CameraModel()
                {
                    Ip = cameraScalesG2.Ip,
                    Name = cameraScalesG2.Name,
                    Port = Convert.ToInt32(cameraScalesG2.Port),
                    PassWord = cameraScalesG2.PassWord,
                    UserName = cameraScalesG2.UserName
                };
                PageShow("cameraModelG2 初始化");
                cameraG2 = new CameraBLL(cameraModelG2);
                cameraG2.ManualOne(pictureBoxG2);
            }
        }

        /// <summary>
        /// 登录抓拍摄像头
        /// </summary>
        private void InitZPCamera()
        {

            cameraG1.ManualOne(pictureBoxG1);
            cameraG2.ManualOne(pictureBoxG2);
        }



        /// <summary>
        /// 获取到车牌的委托事件
        /// </summary>
        /// <param name="carNum"></param>
        /// <param name="cameraIp"></param>
        private void CameraGetCarNum(string carNum, string cameraIp)
        {
            Common.Log4.LogManage.WriteInfo("称重页面拿到了车牌:" + carNum + " 摄像头ip：" + cameraIp);
            SetCarNumInPage(carNum);
            LedPageShow("当前车牌：" + carNum);
            //DoSomthing();
            //***验证车辆

        }

        void SetCarNumInPage(string carNum)
        {
            this.Invoke(new Action(() =>
            {
                textBoxCarNum.Text = carNum;
            }));
        }

        void SetCardNumInPage(string cardNum)
        {
            this.Invoke(new Action(() =>
            {
                textBoxCardNum.Text = cardNum;
            }));
        }

        //led同时显示消息
        private void LedShow(string str)
        {
            onbon6K1CardBLL.SCREEN_SendDynamicArea(str);

        }

        /// <summary>
        /// 车牌号、卡号赋值更新委托
        /// </summary>
        //private void SetCarNum()
        //{

        //    if (!string.IsNullOrEmpty(textBoxCarNum.Text) && !string.IsNullOrEmpty(textBoxCardNum.Text))
        //    {

        //        SearchInfo();
        //    }
        //}

        /// <summary>
        /// 车牌号更新事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void TextBoxCarNum_TextChanged(object sender, EventArgs e)
        //{
        //    Common.DelegateHelper.SetCarNumEvent?.Invoke();
        //}

        /// <summary>
        /// 卡号更新事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void TextBoxCardNum_TextChanged(object sender, EventArgs e)
        //{
        //    Common.DelegateHelper.SetCarNumEvent?.Invoke();
        //}

        /// <summary>
        /// search some info 
        /// </summary>
        //public void SearchInfo()
        //{
        //    try
        //    {
        //        infraredGrating.Open();
        //        string cardNum;
        //        cardNum = textBoxCardNum.Text.Trim();
        //        //查询运销信息并给页面赋值
        //        var YxRes = AutoControlTransportApiServer.GetTruckYxInfo(cardNum);

        //        if (YxRes.data != null)
        //        {
        //            yxYsTransportReturnDto = YxRes.data;
        //            SetText();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        LedPageShow(TipsStringHelper.cxyc);
        //        Common.Log4.LogManage.WriteErr(TipsStringHelper.dbcxan + " " + ex.ToString());
        //        infraredGrating.Close();
        //    }
        //}

        /// <summary>
        /// 抛出异常
        /// </summary>
        /// <param name="str"></param>
        void MessageThrow(string str)
        {
            throw new Exception(str);
        }



        /// <summary>
        ///提示信息显示在led和页面上
        /// </summary>
        /// <param name="str"></param>
        private void LedPageShow(string str)
        {
            LedShow(str);
            PageShow(str);


        }

        /// <summary>
        /// led,页面，异常都显示
        /// </summary>
        /// <param name="str"></param>
        private void LedMessageThrow(string str)
        {
            LedShow(str);
            PageShow(str);
            MessageThrow(str);
        }

        /// <summary>
        /// 提示信息的最大长度
        /// </summary>
        private int InfoMaxLength = Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("InfoMaxLength"));
        /// <summary>
        /// 在显示在页面中的提示信息的长度超过的个数，截取的比例
        /// </summary>
        private int InfoMaxLengthCut = Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("InfoMaxLengthCut"));

        /// <summary>
        /// 页面上显示信息
        /// </summary>
        /// <param name="str"></param>
        private void PageShow(string str)
        {
            //lock (obj)
            //{

            this.Invoke(new Action(() =>
            {
                // textBoxInfo.tex
                int leg = textBoxInfo.TextLength;
                string infoTest = textBoxInfo.Text;
                if (leg > InfoMaxLength)
                {
                    infoTest = infoTest.Substring(leg / InfoMaxLengthCut);
                    textBoxInfo.Text = infoTest;
                }
                textBoxInfo.AppendText("--" + str + "\n");
            }));


        }



        /// <summary>
        /// 页面加载之后需要初始化的所有硬件任务
        /// </summary>
        private void MyInit()
        {


            WeighbridgeId = AppConfigHelper.GetAppSettings("WeighbridgeId");
            weightBZ = Convert.ToDouble(AppConfigHelper.GetAppSettings("weightBZ"));
            weightHaveDate = false;
            redLightState = false;


            InfraredGratingTime = Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("InfraredGratingTime"));
            clearTextTime = Convert.ToInt32(AppConfigHelper.GetAppSettings("ClearTextTime"));
            DelegateHelper.InfoMessageEvent += PageShow;
            Common.DelegateHelper.CameraGetCarNumEvent += CameraGetCarNum;//车牌识别一体机识别到车牌的委托
            Common.DelegateHelper.WeightCallbackEvent += WeightCallback;
            DelegateHelper.InfraredGratingEvent += InfraredGratingEvent1;//红外光栅委托

            InitCamera();
            InitRead();
            IniTrafficLight();
            InitLingSheng();
            InitWagonBalance();
            InitLed();
            InitInfraredGrating();
            InitTimer();
            // Common.DelegateHelper.SetCarNumEvent += SetCarNum;//页面上当车牌号卡号被赋值的时候调用的委托
            yRTReaderBLL.getDataCallbackEvent = GetReadDataCallback;
            Common.DelegateHelper.SendWidthHeightEvent += SendWidthHeight;


        }
        private void SendWidthHeight(int Width, int height)
        {
            if (wFAutoSizeHelper.ControlsInfo.Count > 0)//如果字典中有数据，即窗体改变
            {
                wFAutoSizeHelper.ControlsChangeInit(Width, height);//表示pannel控件
                wFAutoSizeHelper.ControlsChange(this.Controls[0]);
            }
        }

        private void InitTimer()
        {
            rePeatCardNumTimer.Elapsed += RePeatCardNumTimer_Elapsed;
            rePeatCardNumTimer.Enabled = true;
            rePeatCardNumTimer.AutoReset = false;
            rePeatCardNumTimer.Start();

            //noCarTimer.Elapsed += NoCarTimer_Elapsed;
            //noCarTimer.Enabled = true;
            //noCarTimer.AutoReset = false;
            //noCarTimer.Start();
        }

        private void NoCarTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            string carNum = textBoxCarNum.Text.Trim();
            string cardNum = textBoxCardNum.Text.Trim();
            if (!string.IsNullOrEmpty(carNum) || !string.IsNullOrEmpty(cardNum))
            {
                if (nowWeight < 1)
                {
                    ClearText();
                }
                else
                {
                    noCarTimer.Start();
                }

            }

        }

        private void RePeatCardNumTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
        }

        private void InitRead()
        {
            yRTReaderBLL = new HardWareBLL.YRTReaderBLL();
            // yRTReaderBLL.getDataCallbackEvent = GetReadDataCallback;
        }
        /// <summary>
        /// 在页面设置卡号
        /// </summary>
        void SetCardNum(string str)
        {
            this.Invoke(new Action(() =>
            {
                textBoxCardNum.Text = str;
            }));
        }
        /// <summary>
        /// 读卡器数据的回调
        /// </summary>
        /// <param name="epc"></param>
        private void GetReadDataCallback(string epc)
        {
            lock (obj)
            {
                string reaStr = epc.Substring(0, 12);
                SetCardNum(reaStr);
                if (cardNumNow == epc)
                {
                    if (rePeatCardNumTimer.Enabled)
                    {
                        PageShow("当前卡号重复，倒计时还在继续！");
                    }
                    else
                    {
                        if (epc.Length != 12)
                        {
                            LedPageShow(epc);
                            return;
                        }
                        DoSomthing();
                    }
                }
                else
                {
                    cardNumNow = epc;
                    if (epc.Length != 12)
                    {
                        LedPageShow(epc);
                        return;
                    }
                    LedPageShow("当前卡号：" + reaStr);
                    DoSomthing();
                }
            }
        }

        /// <summary>
        /// 查询并判断流程
        /// </summary>
        void DoSomthing()
        {
            try
            {

                if (!rePeatCardNumTimer.Enabled)
                {
                    rePeatCardNumTimer.Start();
                }
                if (!noCarTimer.Enabled)
                {
                    noCarTimer.Start();
                }
                //infraredGrating.Open();
                string cardNum = textBoxCardNum.Text.Trim();
                string carNum = textBoxCarNum.Text.Trim();
                double ww = nowWeight;
                //textBoxCZZL.Text = nowWeight.ToString();
                Common.Log4.LogManage.WriteWarn("车牌：" + carNum + " 卡号：" + cardNum + " 重量：" + ww);


                if (!string.IsNullOrWhiteSpace(cardNum) && !string.IsNullOrWhiteSpace(carNum))
                {
                    //地磅数据是否达标
                    if (nowWeight < weightBZ)
                    {
                        MessageThrow("地磅重量不达标！");
                    }
                    //weightHaveDate = true;
                    //获取信息赋值
                    Models.GetTruckYxInfoSendM getTruckYxInfoSendM = new Models.GetTruckYxInfoSendM()
                    {
                        cardNo = cardNum,
                        truckNo = carNum,
                        imgs1 = ""
                    };
                    var resGetTruckYxInfo = AutoControlTransportApiServer.GetTruckYxInfo(getTruckYxInfoSendM);
                    if (!resGetTruckYxInfo.success)
                    {
                        MessageThrow(resGetTruckYxInfo.msg);
                    }
                    yxYsTransportReturnDto = resGetTruckYxInfo.data == null ? new Models.GetTruckYxInfoRceiveM() : resGetTruckYxInfo.data;
                    SetText();

                    InfraredGratingJudge();

                    //获取监控的图片
                    List<string> picCodeList = new List<string>();
                    string picG1 = cameraG1.UpLoadFile();
                    if (!string.IsNullOrWhiteSpace(picG1))
                    {
                        picCodeList.Add(picG1);
                    }
                    string picG2 = cameraG2.UpLoadFile();
                    if (!string.IsNullOrWhiteSpace(picG2))
                    {
                        picCodeList.Add(picG2);
                    }
                    string imgs1 = string.Join(",", picCodeList);

                    //除皮接口
                    Models.TareDtoSendM admissionDtoSendM = new Models.TareDtoSendM()
                    {
                        cardNo = cardNum,
                        truckNo = carNum,
                        imgs1 = imgs1,
                        pz = ww,
                        wgbid = Convert.ToInt32(WeighbridgeId)
                    };
                    var resM = AutoControlTransportApiServer.TruckTare(admissionDtoSendM);
                    if (!resM.success)
                    {
                        MessageThrow(resM.msg);
                    }
                    cameraQ.BarrierGateControl(1);
                    lingShengAudio.AutoStartTask(Convert.ToInt32(AppConfigHelper.GetAppSettings("LingShengTaskId")));
                    LedPageShow("除皮成功，请下磅!当前" + ww + "吨");
                    // ClearText();
                }
            }
            catch (Exception ex)
            {
                LedPageShowLog(ex);
            }
            finally
            {
                // infraredGrating.Close();
            }
        }

        private void LedPageShowLog(Exception ex)
        {
            LedShow(ex.Message);
            PageShow(ex.Message);
            Common.Log4.LogManage.WriteErr(ex.ToString());
        }

        private void LightWeight_Load(object sender, EventArgs e)
        {
            MyInit();
        }
    }
}
